package com.gcu.drivingschool.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import com.gcu.drivingschool.domain.vo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 参数校验异常
     * @param ex
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    //设置浏览器响应状态码400
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleValidationException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        List<String> errorMessages = new ArrayList<>();
        for (FieldError fieldError : fieldErrors) {
            errorMessages.add(fieldError.getField()+":"+fieldError.getDefaultMessage());
        }
        return Result.fail(400, "参数校验错误", errorMessages);
    }

    /**
     * 参数格式转换异常
     * @param ex
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    //设置浏览器响应状态码400
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        return Result.fail(400, "参数格式错误", ex.getMessage());
    }

    /**
     * 认证失败异常
     * @param ex
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)//401
    public Result handleAuthenticationException(NotLoginException ex){
        return Result.fail(400,"认证失败",ex.getMessage());
    }

//    /**
//     * 服务异常
//     * @return
//     */
//    @ExceptionHandler(RuntimeException.class)
//    //设置浏览器响应状态码500
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    public Result handleException(RuntimeException ex){
//        return Result.fail(400,"服务异常",ex.getMessage());
    //}
}